package net.qiqb.module.dubbo;

import net.qiqb.module.ModuleServiceDispatcher;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.springframework.beans.factory.BeanFactory;

public class DubboServiceGateway implements ModuleServiceDispatcher {


    private final BeanFactory beanFactory;

    public DubboServiceGateway(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public <T> void dispatch(Class<T> interfaceClass, T service) {
        ModuleModel moduleModel = DubboBeanUtils.getModuleModel(beanFactory);
        if (moduleModel == null) {
            return;
        }
        ServiceConfig<T> serviceConfig = new ServiceConfig<>();
        serviceConfig.setInterface(interfaceClass);
        serviceConfig.setRef(service);
        moduleModel.getConfigManager().addService(serviceConfig);

        moduleModel.getDeployer().setPending();
    }

    @Override
    public <T> T refer(Class<T> interfaceClass) {
        ModuleModel moduleModel = DubboBeanUtils.getModuleModel(beanFactory);
        if (moduleModel == null) {
            return null;
        }
        ReferenceConfig<T> reference = new ReferenceConfig<>();
        reference.setInterface(interfaceClass);
        reference.setCheck(false);
        moduleModel.getConfigManager().addReference(reference);
        return reference.get();
    }
}
